package client;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Server-side for Client-Client communication. (needed for timestamp-requests)
 * 
 * @author Lukas
 *
 */
public class TimestampListener extends Thread {
	private int port;
    private ExecutorService pool;
    private boolean running = true;
    private ServerSocket ss;
    
    /**
     * Constructor.
     * @param port The port on which shall be listened.
     */
    public TimestampListener(int port) {
    	this.port = port;
    	start();
    }
	
	@Override
	public void run() {
		try {
	        pool= Executors.newCachedThreadPool();
			ss = new ServerSocket(port);
		} catch (IOException e) {
			System.out.println("Timestamp request listener not created");
			return;
		}
        while(running){
            try {
                pool.execute(new TimestampHandler(ss.accept()));
                System.out.println("new Client accepted");
            } catch (SocketException se) {
                //Socket Terminated, shutdown thread
                running = false;
            } catch (IOException e) {
                running = false;
                System.out.println("Error on Thread Creation: "+e.getMessage());
            }
        }
        pool.shutdown();
	}
    
    /**
     * Shutdown the Thread
     */
    public void shutdown() {
        running = false;
        try {
            ss.close();
        } catch (IOException e) {
           System.out.println("Error: "+e.getMessage());
        }
    }
}
